package cz.najman.emdroid.connection;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import android.util.Log;
import cz.najman.emdroid.content.ContentHandler;
import cz.najman.emdroid.exception.ParsingException;

/**
 * @author  Lukáš Najman
 */
public class ParsableResponseHandler extends AbstractResponseHandler {
	private static final String TAG = "ParsableResponseHandler";
	
	/**
	 */
	ContentHandler mHandler;
	XMLReader mReader;	
		
	public ParsableResponseHandler() throws SAXException, ParserConfigurationException {
		mReader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
	}	
	
	public ParsableResponseHandler(ContentHandler mHandler) throws SAXException, ParserConfigurationException {	
		this();
		this.mHandler = mHandler;		
	}
	
	@Override
	public Integer handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
		
		Log.d(TAG, ">>> Entering response handler");
		mResponseCode = response.getStatusLine().getStatusCode();
		if( (mResponseCode >= 200) && (mResponseCode < 300) ){	
			
				if(mHandler != null){
					mHandler.setRequestId(mRequestId);
					mHandler.setListener(mListener);
					try {
						parse(response);
					} catch (SAXException e) {
						throw new ParsingException(e.getCause());
					}
											
					
				} else {
					mListener.onParsedDataReceive(null, mRequestId);
				}
			
		} else {
			InputStream in = response.getEntity().getContent();
			Writer writer = new StringWriter();
						 
			char[] buffer = new char[1024];
			
			try {
				Reader reader = new BufferedReader(
				new InputStreamReader(in, "UTF-8"));
				int n;
				while ((n = reader.read(buffer)) != -1) {
					writer.write(buffer, 0, n);
				}
			} finally {
				in.close();
			}
			String str = writer.toString();
			Log.d(TAG, str);
		}
		
		return mResponseCode;	
		
	}
	
	public void setContenthandler(ContentHandler handler){
		mHandler = handler;
	}
	
	private void parse(HttpResponse response) throws IOException, SAXException {
		
		Log.d(TAG, "Start parcing");
		final HttpEntity entity = response.getEntity();
		InputStream content = entity.getContent();		
		
		mReader.setContentHandler(mHandler);
		mReader.parse(new InputSource(content));
		
		content.close();
		content = null;
		entity.consumeContent();		
	}

	
	
}
